//
//  DLInformationVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/22.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLInformationVC.h"
#import "DLClassifyListModel.h"
#import "DLInfoBgScrollView.h"
#import "DLInfoListModel.h"
#import "DLInfoBgView.h"
#import "DLInformationSearchVC.h"

@interface DLInformationVC ()<MSSegmentViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) MSSegmentView *infoSegmentView;

@property (nonatomic, strong) DLInfoBgScrollView *infoBgScrollView;

@property (nonatomic, strong) NSMutableArray *classifyListDataSource;

@property (nonatomic, strong) NSMutableArray *infoListDataSource;

@property (nonatomic, strong) NSMutableArray *loadedClassify;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, assign) NSInteger svPageIndex;

@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation DLInformationVC

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setUpNav];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(responseCodeError) name:@"HTTPMustUpdateAppVersion" object:nil];
}
- (void) responseCodeError {
    
    [self endAllRefresh];
}
- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    kuserManager.currentTabIndex = 1;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    
    [self initDataSource];
    
    [self layoutSubControls];
    [self loadClassifyData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadNewInfoData:) name:@"DLReloadNewInfoData" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMoreInfoData:) name:@"DLLoadMoreInfoData" object:nil];
}


- (void) reloadNewInfoData:(NSNotification*)notify {
    NSString *pageStr = [NSString stringWithFormat:@"%@", notify.object];
    self.pageNum = pageStr.integerValue;
    self.infoSegmentView.userInteractionEnabled = NO;
    self.infoBgScrollView.userInteractionEnabled = NO;
    DLClassifyListModel *model = self.classifyListDataSource[self.svPageIndex];
    NSLog(@"下拉刷新%ld", self.pageNum);
    [self loadInfoListDataWithClassifyId:model.name];
}
- (void) loadMoreInfoData:(NSNotification*)notify {
    
    NSString *pageStr = [NSString stringWithFormat:@"%@", notify.object];
    self.pageNum = pageStr.integerValue;
    self.infoSegmentView.userInteractionEnabled = NO;
    self.infoBgScrollView.userInteractionEnabled = NO;
    DLClassifyListModel *model = self.classifyListDataSource[self.svPageIndex];
    NSLog(@"上拉加载%ld", self.pageNum);
    [self loadInfoListDataWithClassifyId:model.name];
}

- (void) loadInfoListDataWithClassifyId:(NSString *)classifyId {
    
    NSString *uniqueId = [DLKeyChainManager readUUID];
    if (isEmpty(uniqueId)) {
        uniqueId = [DLKeyChainManager createUUID];
        [DLKeyChainManager saveUUID:uniqueId];
    }
    
    
    NSString *postUrl = HTTPInformationList;
    NSDictionary *postDic = @{
                              @"user_id" : kuserManager.isLogin?kuserManager.userInfoModel.userid:uniqueId,
                              @"classify" : classifyId,
                              @"page" : @(self.pageNum),
                              @"ignore" : @""
                              };
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.labelText = @"加载中···";
    self.hud = hud;

    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        [hud hide:YES];
        if (kRequestSuccess(responseObject)) {
            NSArray *arr = responseObject[@"result"];
            if (arr.count > 0) {
                
                NSMutableArray *mutArr;
                for (NSInteger i = 0; i < self.infoListDataSource.count; i++) {
                    NSDictionary *dic = self.infoListDataSource[i];
                    
                    NSArray *keysArr = [dic allKeys];
                    
                    NSString *keyString = keysArr[0];
                    
                    if ([keyString isEqualToString:[NSString stringWithFormat:@"%ld", self.infoSegmentView.currentItemIndex]]) {
                        
                        mutArr = [NSMutableArray arrayWithArray:dic[keyString]];
                    }
                }
                if (self.pageNum == 1) {
                    
                    [mutArr removeAllObjects];
                }
                
                
                for (NSInteger i = 0; i < arr.count; i++) {
                    NSDictionary *dic = arr[i];
                    DLInfoListModel *infoListModel = [DLInfoListModel mj_objectWithKeyValues:dic];
                    
                    DLClassifyListModel *mclassifyListModel = self.classifyListDataSource[self.infoSegmentView.currentItemIndex];
                    infoListModel.fatherClassify = mclassifyListModel.ID;
                    infoListModel.isZhiXunShowAll = NO;
                    [mutArr addObject:infoListModel];
                }
//                NSLog(@"当前点击的这个分类的数据源：%@", mutArr);
                
                
                for (NSInteger i = 0; i < self.infoListDataSource.count; i++) {
                    NSDictionary *dic = self.infoListDataSource[i];
                    NSArray *keysArr = [dic allKeys];
                    NSString *keyString = keysArr[0];
                    
                    if ([keyString isEqualToString:[NSString stringWithFormat:@"%ld", self.infoSegmentView.currentItemIndex]]) {
                        NSDictionary *newDataDic = @{keyString : mutArr};
                        [self.infoListDataSource replaceObjectAtIndex:i withObject:newDataDic];
                    }
                }
                
//                self.infoBgScrollView.infoDataSource = mutArr;
                [self.infoBgScrollView updateInfoWithCurrentPage:self.infoSegmentView.currentItemIndex andDataSource:mutArr];
            } else {
                if (self.pageNum > 1) {
                    self.pageNum--;
                }
            }
            
        } else {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            if (self.pageNum > 1) {
                self.pageNum--;
            }
        }
        [self endAllRefresh];
        
    } failure:^(NSError * _Nonnull error) {
        [hud hide:YES];
        NSLog(@"请求接口失败，错误是：%@", error);
        if (self.pageNum > 1) {
            self.pageNum--;
        }
        [self endAllRefresh];
        
//        self.showNetworkErrorView = YES;
    }];
}
- (void) networkRetryyyy {
    
    NSLog(@"重新加载资讯数据");
    [self loadClassifyData];
}
- (void) endAllRefresh {
    //一定要用通知 不能调很多次.语法 不然有时候刷新的动画还在，table不回去，就有问题了
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DLInfoTableViewEndRefreshing" object:nil];
    self.infoSegmentView.userInteractionEnabled = YES;
    self.infoBgScrollView.userInteractionEnabled = YES;
    [self.hud hide:YES];
}

- (void) loadClassifyData {
    
    NSString *uniqueId = [DLKeyChainManager readUUID];
    if (isEmpty(uniqueId)) {
        uniqueId = [DLKeyChainManager createUUID];
        [DLKeyChainManager saveUUID:uniqueId];
    }
    
    NSString *postUrl = HTTPInformationClassify;
    NSDictionary *postDic = @{
                              @"user_id" : kuserManager.isLogin?kuserManager.userInfoModel.userid:uniqueId
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            
            NSArray *arr = responseObject[@"result"];
            if (arr.count > 0) {
                
                [self.classifyListDataSource removeAllObjects];
                for (NSDictionary *dic in arr) {
                    
                    DLClassifyListModel *classifyListModel = [DLClassifyListModel mj_objectWithKeyValues:dic];
                    [self.classifyListDataSource addObject:classifyListModel];
                }
                //配置segment
                self.infoSegmentView.itemTitles = arr;
                [self.infoSegmentView updateData];
                self.infoSegmentView.currentItemIndex = 0;
                
                
                //配置scrollview
                self.infoBgScrollView.contentSize = CGSizeMake(kScreenWidth *arr.count, self.infoBgScrollView.height);
            }
            
        } else {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
        }
        
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
        kuserManager.lastVc.showNetworkErrorView = YES;
    }];
    
}
- (void) layoutSubControls {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
//    normal_navbg
    UIImageView *falseNavView = [UIImageView new];
    falseNavView.frame = CGRectMake(0, 0, kScreenWidth, kHeightNavigation);
    falseNavView.image = [UIImage imageNamed:@"info_navbg"];
    [self.view addSubview:falseNavView];
    falseNavView.userInteractionEnabled = YES;
    
    //为1.0版本上线改的，如想改回原版本，注释下方代码即可
//    MSSegmentView *infoSegmentView = [[MSSegmentView alloc] initWithFrame:CGRectMake(0,kHeightNavigationStatusBar, kScreenWidth - kAutoWidth(70), kHeightNavigation - kHeightNavigationStatusBar)];
    MSSegmentView *infoSegmentView = [[MSSegmentView alloc] initWithFrame:CGRectMake(0,kHeightNavigationStatusBar, kScreenWidth, kHeightNavigation - kHeightNavigationStatusBar)];
    infoSegmentView.backgroundColor = [UIColor clearColor];
    infoSegmentView.ImageType = MSSegmentBtnImageTypeLeft;
    infoSegmentView.textColor = [UIColor whiteColor];
    infoSegmentView.textSelColor = [UIColor whiteColor];
    infoSegmentView.font = kSystemFont(13);
    infoSegmentView.selFont = kSystemFont(18);
    infoSegmentView.delegate = self;
    infoSegmentView.layer.shadowColor = [UIColor grayColor].CGColor;
    infoSegmentView.layer.shadowOpacity = 0.5f;
    infoSegmentView.layer.shadowRadius = 4.f;
    infoSegmentView.itemImages = @[];
    
    infoSegmentView.lineColor = [UIColor whiteColor];
    infoSegmentView.lineExWidth = 2;
    [falseNavView addSubview:infoSegmentView];
    self.infoSegmentView = infoSegmentView;
    
    UIView *rightToolsView = [UIView new];
    rightToolsView.frame = CGRectMake(infoSegmentView.right, infoSegmentView.top, kScreenWidth - infoSegmentView.width, infoSegmentView.height);
    rightToolsView.backgroundColor = [UIColor clearColor];
    [falseNavView addSubview:rightToolsView];
    
    UIButton *infoSearchBtn = [UIButton buttonWithType:0];
    infoSearchBtn.adjustsImageWhenHighlighted = NO;
    infoSearchBtn.frame = CGRectMake(0, 0, rightToolsView.height - kAutoWidth(10), rightToolsView.height);
    [infoSearchBtn setImage:[UIImage imageNamed:@"info_search"] forState:UIControlStateNormal];
    [infoSearchBtn addTarget:self action:@selector(infoSearchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [rightToolsView addSubview:infoSearchBtn];
    
    UIButton *machineBtn = [UIButton buttonWithType:0];
    machineBtn.frame = CGRectMake(rightToolsView.width - kAutoWidth(37), (rightToolsView.height - 40 * 2 /3) / 2, 40 * 2 / 3, 40 * 2 /3);
    [machineBtn setImage:[UIImage imageNamed:@"info_robot"] forState:UIControlStateNormal];
    [machineBtn addTarget:self action:@selector(machineBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [rightToolsView addSubview:machineBtn];
    machineBtn.adjustsImageWhenHighlighted = NO;
    
    
    DLInfoBgScrollView *infoBgScrollView = [[DLInfoBgScrollView alloc] initWithFrame:CGRectMake(0, kHeightNavigation, kScreenWidth, kScreenSafeAreaHeight - kHeightTabBar - kHeightNavigation)];
    infoBgScrollView.delegate = self;
    infoBgScrollView.pagingEnabled = YES;
    infoBgScrollView.backgroundColor = [UIColor whiteColor];
    infoBgScrollView.bounces = NO;
    infoBgScrollView.showsVerticalScrollIndicator = NO;
    infoBgScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:infoBgScrollView];
    self.infoBgScrollView = infoBgScrollView;
    
    
    
    
    
    //为1.0版本上线改的，如想改回原版本，注释下方代码即可
    falseNavView.image = [UIImage imageNamed:@"normal_navbg"];
    
    rightToolsView.hidden = YES;
    
    infoSegmentView.selFont = kSystemFont(18);
    infoSegmentView.lineColor = [UIColor clearColor];
    infoSegmentView.lineExWidth = 0.001;
}

- (void) machineBtnClick {
    DLMachineDetailVC *machineDetailVC = [DLMachineDetailVC new];
    [self.navigationController pushViewController:machineDetailVC animated:YES];
    
}
- (void) infoSearchBtnClick {
    
    DLInformationSearchVC *isvc = [DLInformationSearchVC new];
    [self.navigationController pushViewController:isvc animated:YES];
}

- (void) itemDidSelectedWithIndex:(NSInteger)index withCurrentIndex:(NSInteger)currentIndex {
    
    self.infoSegmentView.currentItemIndex = index;
    //当index 和 currentIndex相同的时候 需要刷新当前页数据，不同的时候 看之前点过这个index没 如果点过 就不刷新，没点过 就刷新
    self.svPageIndex = index;
    
    DLClassifyListModel *model = self.classifyListDataSource[index];
    NSString *currentClassiifyId = model.ID;
    
    if (index == currentIndex) {
        
        NSLog(@"********当前停留的分类和点击的分类是一个，刷新数据");
        self.pageNum = 1;
        [self configDataSource];
        
        [self loadInfoListDataWithClassifyId:model.name];
        
    } else {
        
        if (![self.loadedClassify containsObject:currentClassiifyId]) {
            NSLog(@"********当前停留的分类和点击的分类不同，并且新点击的分类之前没点击过，要刷新数据");
            self.pageNum = 1;
            [self configDataSource];
            
            [self loadInfoListDataWithClassifyId:model.name];
        } else {
            NSLog(@"********当前停留的分类和点击的分类不同，并且新点击的分类之前已经加载过数据了");
        }
    }
    
    if (![self.loadedClassify containsObject:currentClassiifyId]) {
//        NSLog(@"********当前点击这个分类从来没点击过，这次点击了，要记录下来");
        [self.loadedClassify addObject:currentClassiifyId];
        
    }
    
    self.infoBgScrollView.contentOffset = CGPointMake(kScreenWidth * index, 0);
}

- (void) scrollViewDidScroll:(UIScrollView *)scrollView {
    
    NSInteger currentPage = (scrollView.contentOffset.x + kScreenWidth / 2) / kScreenWidth;
    
    self.infoSegmentView.currentItemIndex = currentPage;
    
    self.svPageIndex = currentPage;
    
//    [self endAllRefresh];
}
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger currentPage = (scrollView.contentOffset.x + kScreenWidth / 2) / kScreenWidth;
    
    self.infoSegmentView.currentItemIndex = currentPage;
    
    self.svPageIndex = currentPage;
    
    DLClassifyListModel *model = self.classifyListDataSource[currentPage];
    NSString *currentClassiifyId = model.ID;
    
    
//    [self endAllRefresh];
    
    if (![self.loadedClassify containsObject:currentClassiifyId]) {
        NSLog(@"^^^^^^^^当前停留页之前没滚动到过或者点击刷新过数据，要刷新数据");
        self.pageNum = 1;
        [self configDataSource];
        
        [self loadInfoListDataWithClassifyId:model.name];
    } else {
        NSLog(@"^^^^^^^^当前停留之前已经加载过数据了");
    }
    if (![self.loadedClassify containsObject:currentClassiifyId]) {
        NSLog(@"^^^^^^^^当前滚动到的这个分类从来没点击或滚动到过，这次滚动到了，要记录下来");
        [self.loadedClassify addObject:currentClassiifyId];
        
    }
}

- (void) configDataSource {
    NSString *currentIndex4String = [NSString stringWithFormat:@"%ld", self.infoSegmentView.currentItemIndex];
    
    NSMutableArray *dataSourceArray = [NSMutableArray array];
    NSDictionary *pageDic = @{currentIndex4String : dataSourceArray};
    
    BOOL isExist = NO;
    for (NSInteger i = 0; i < self.infoListDataSource.count; i++) {
        
        NSDictionary *originDic = self.infoListDataSource[i];
        NSArray *keyArr = [originDic allKeys];
        NSString *keyStr = keyArr[0];
        
        if ([keyStr isEqualToString:currentIndex4String]) {
            isExist = YES;
        }
    }
    
    if (isExist == NO) {
        //数据源里没有存当前点击的index作为key的字典
        [self.infoListDataSource addObject:pageDic];
    }
    
    NSLog(@"***********%@", self.infoListDataSource);
}



- (void) setUpNav {
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.translucent = YES;
}

- (void) initDataSource {
    
    self.classifyListDataSource = [NSMutableArray array];
    self.infoListDataSource = [NSMutableArray array];
    self.loadedClassify = [NSMutableArray array];
    self.pageNum = 1;
    
    NSMutableArray *mutArr = [NSMutableArray array];
    [self.infoListDataSource addObject:@{@"0" : mutArr}];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
